# coding: utf-8
from urllib import request
import re, zlib
import asyncio
import time

async def async_get_html2(url):
	return request.urlopen(url).read()

def get_html2(url):
	return request.urlopen(url).read()

async def async_get_html(url):
	headers = {
		"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3269.3 Safari/537.36"
		}
	req = request.Request(url, headers = headers)
	resp = request.urlopen(req)
	html = resp.read()
	if resp.headers.get('Content-Encoding') == 'gzip':
		html = zlib.decompress(html ,16+zlib.MAX_WBITS)
	try:
		html = str(html, encoding='utf-8')
	except:
		html = str(html, encoding='gbk')
	return html

def re_title(html):
	title = re.findall(r'(?<=\<title\>).+?(?=\<)', html, re.S)
	if title:
		return title[0]
	else:
		return "not found"

async def async_get_video_title(url):
	html = await async_get_html(url)
	return re_title(html)

def async_get_wallpapers(cid, start, count):
	if cid == "360new":
		start = start or 0
		count = count or 0
		url = "http://wallpaper.apc.360.cn/index.php?c=WallPaper&a=getAppsByOrder&order=create_time&start=%s&count=%s&from=360chrome" % (start, count)
	elif cid == "360tags":
		url = "http://cdn.apc.360.cn/index.php?c=WallPaper&a=getAllCategoriesV2&from=360chrome"
	elif cid == "bing":
		start = start or -1
		count = count or 8
		url = "http://cn.bing.com/HPImageArchive.aspx?format=js&idx=%s&n=%s" % (start, count)
	else:
		start = start or 0
		count = count or 10
		url = "http://wallpaper.apc.360.cn/index.php?c=WallPaper&a=getAppsByCategory&cid=%s&start=%s&count=%s&from=360chrome" % (cid, start, count)
	# res = await async_get_html2(url)
	# return run_coroutine(async_get_html2, url)
	return get_html2(url)
	# return res

def run_coroutine(coroutine, *args):
	try:
		coroutine(*args).send(None)
	except StopIteration as e:
		return e.value

if __name__ == "__main__":
	url = "http://fanyi.baidu.com"
	get_video_title(url)
	pass